package com.selly.hanjuang;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.selly.hanjuang.lib.JSONParser;
import com.selly.hanjuang.lib.MyApplication;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class NewOrderActivity extends Activity {

	final Context context = this;

	// Progress Dialog
	// private ProgressDialog pDialog;

	JSONParser jsonParser = new JSONParser();

	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();
	// ArrayList<HashMap<String, String>> DaftarPropinsi;

	// 
	// private static String url_daftar_produk =
	// "http://10.0.2.2/hanjuang/json/daftar_produk.php";
	private static String url_daftar_propinsi = "http://hanjuang.web.id/json/daftar_provinsi.php";
	private static String url_daftar_kota = "http://hanjuang.web.id/json/daftar_kota.php";

	// JSON Node names
	// public static final String TAG_SUCCESS = "success";
	public static final String TAG_DAFTAR_PROPINSI = "daftar_propinsi";
	public static final String TAG_DAFTAR_KOTA = "daftar_kota";
	public static final String TAG_ID_EKSPEDISI = "id_ekspedisi";
	public static final String TAG_PROPINSI = "propinsi";
	public static final String TAG_KOTA = "kota";
	public static final String TAG_HARGA = "harga";

	// Button ButtonAddTocart;

	// daftar_produk JSONArray
	JSONArray daftar_propinsi = null;
	JSONArray daftar_kota = null;

	EditText inputNamaPemesan;
	EditText inputAlamat;
	// EditText inputProvinsi;
	// EditText inputKota;
	EditText inputEmail;
	EditText inputTelp;
	Spinner spinnerProvinsi;
	Spinner spinnerKota;

	// url to create new pemesanan
	// String localhost = ((MyApplication)
	// this.getApplication()).getLocalhost();
	// private String url_create_pemesanan =
	// "http://10.0.2.2/hanjuang/json/create_pemesanan.php";
	// private String url_create_detail_pemesanan =
	// "http://10.0.2.2/hanjuang/json/create_detail_pemesanan.php";
	private String url_create_pemesanan = "http://hanjuang.web.id/json/create_pemesanan.php";
	private String url_create_detail_pemesanan = "http://hanjuang.web.id/json/create_detail_pemesanan.php";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";

	ArrayList<Provinsi> provinsies = new ArrayList<Provinsi>();
	ArrayList<Kota> kotas = new ArrayList<Kota>();

	String[] namaProvinsi;
	String[] namaKota;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_product);

		// Edit Text
		inputNamaPemesan = (EditText) findViewById(R.id.inputNamaPemesan);
		inputAlamat = (EditText) findViewById(R.id.inputAlamat);
		// inputProvinsi = (EditText) findViewById(R.id.inputProvinsi);
		// inputKota = (EditText) findViewById(R.id.inputKota);
		inputEmail = (EditText) findViewById(R.id.inputEmail);
		inputTelp = (EditText) findViewById(R.id.inputTelp);

		spinnerProvinsi = (Spinner) findViewById(R.id.spinnerProvinsi);
		spinnerKota = (Spinner) findViewById(R.id.spinnerKota);

		loadPropinsi();

		// Create button
		Button btnCreatePesan = (Button) findViewById(R.id.btnPesan);

		// button click event
		btnCreatePesan.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				// creating new pemesanan in background thread
				new CreateNewPemesanan().eksekusi();
			}
		});

		// String readFeed = null; // = readFeed();

		/*
		 * ArrayList<Provinsi> provinsies = new ArrayList<Provinsi>();
		 * ArrayList<String> provinsiNames = new ArrayList<String>();
		 * 
		 * try { JSONObject json = new JSONObject(readFeed); JSONArray jsonArray
		 * = new JSONArray(json.optString("provinsi"));
		 * Log.i(NewOrderActivity.class.getName(), "Number of entries " +
		 * jsonArray.length());
		 * 
		 * for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject
		 * = jsonArray.getJSONObject(i);
		 * 
		 * Provinsi provinsi = new Provinsi();
		 * 
		 * } } catch (Exception e) { e.printStackTrace(); }
		 */

		// Hashmap for ListView
		// DaftarPropinsi = new ArrayList<HashMap<String, String>>();

		// loading daftar

	}

	protected void submitDetailPemesanan() {
		// TODO Auto-generated method stub
		ArrayList<Bandrek> bandrekList = ((MyApplication) this.getApplication())
				.getBandrekList();

		String s = String.valueOf(bandrekList.size());
		Log.d("cek jumlah BandrekList ", s);

		int grandTotal = ((MyApplication) this.getApplication())
				.getGrandTotal();

		boolean lastBandrek = false;
		for (int i = 0; i < bandrekList.size(); i++) {
			Bandrek bandrek = bandrekList.get(i);
			if (i == bandrekList.size() - 1) {
				lastBandrek = true;
			}
			CreateNewPemesananDetail cnpd = new CreateNewPemesananDetail(
					bandrek, lastBandrek, grandTotal);
			cnpd.detailExecute();
		}
	}

	/**
	 * Background Async Task to Create new pemesanan
	 * */
	class CreateNewPemesanan {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		/*
		 * @Override protected void onPreExecute() { super.onPreExecute();
		 * pDialog = new ProgressDialog(NewOrderActivity.this);
		 * pDialog.setMessage("Submit Pemesanan..");
		 * pDialog.setIndeterminate(false); pDialog.setCancelable(true);
		 * pDialog.show(); }
		 */

		/**
		 * Creating pemesanan
		 * */
		protected String eksekusi() {
			/* yg pertama */
			String namaPemesan = inputNamaPemesan.getText().toString();
			String alamat = inputAlamat.getText().toString();
			String provinsi = spinnerProvinsi.getSelectedItem().toString();
			String kota = spinnerKota.getSelectedItem().toString();
			String email = inputEmail.getText().toString();
			String telp = inputTelp.getText().toString();

			if (namaPemesan.equals("")) {
				showCustomDialog2("Nama Pemesan tidak boleh kosong!");
			} else if (alamat.equals("")) {
				showCustomDialog2("Alamat tidak boleh kosong!");
			} else if (email.equals("")) {
				showCustomDialog2("Email tidak boleh kosong!");
			} else if (telp.equals("")) {
				showCustomDialog2("Telp tidak boleh kosong!");
			} else {
				// Building Parameters
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("nama_pemesan", namaPemesan));
				params.add(new BasicNameValuePair("alamat", alamat));
				params.add(new BasicNameValuePair("provinsi", provinsi));
				params.add(new BasicNameValuePair("kota", kota));
				params.add(new BasicNameValuePair("email", email));
				params.add(new BasicNameValuePair("telp", telp));

				// getting JSON Object
				// Note that create pemesanan url accepts POST method
				JSONObject json = jsonParser.makeHttpRequest(
						url_create_pemesanan, "POST", params);

				// check log cat fro response
				Log.d("Create Response", json.toString());

				// check for success tag
				try {
					int success = json.getInt(TAG_SUCCESS);

					if (success == 1) {
						/*
						 * Intent a = new Intent(getApplicationContext(),
						 * MenuPemesanan.class);
						 * a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
						 * Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(a);
						 * 
						 * finish();
						 */
						Log.d("pemesanan", "submit pemesanan sukses");
						submitDetailPemesanan();

						showCustomDialog();

					} else {
						// failed to create product
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		/*
		 * protected void onPostExecute(String file_url) { // dismiss the dialog
		 * once done pDialog.dismiss();
		 * 
		 * 
		 * }
		 */

	}

	/**
	 * Background Async Task to Create new pemesanan
	 * */
	class CreateNewPemesananDetail {

		Bandrek bandrek;
		boolean lastProduct;
		int grandTotal;

		public CreateNewPemesananDetail(Bandrek bandrek, boolean lastProduct,
				int grandTotal) {
			// TODO Auto-generated constructor stub
			this.bandrek = bandrek;
			this.lastProduct = lastProduct;
			this.grandTotal = grandTotal;
		}

		protected String detailExecute() {
			String namaPemesan = inputNamaPemesan.getText().toString();
			String alamat = inputAlamat.getText().toString();
			// String provinsi = inputProvinsi.getText().toString();
			// String kota = inputKota.getText().toString();
			String provinsi = spinnerProvinsi.getSelectedItem().toString();
			String kota = spinnerKota.getSelectedItem().toString();
			String email = inputEmail.getText().toString();
			String telp = inputTelp.getText().toString();

			// Building Parameters

			/* yg pertama */
			String id_produk = bandrek.getId_product();
			String jumlah = String.valueOf(bandrek.getQty());
			Log.d("jumlah cik", jumlah);
			// String id_ekspedisi = "324238";
			String totalbeli = String.valueOf(bandrek.getTotalHarga());

			// id_produk, jumlah, id_ekspedisi

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("nama_pemesan", namaPemesan));
			params.add(new BasicNameValuePair("alamat", alamat));
			params.add(new BasicNameValuePair("provinsi", provinsi));
			params.add(new BasicNameValuePair("kota", kota));
			params.add(new BasicNameValuePair("email", email));
			params.add(new BasicNameValuePair("telp", telp));

			params.add(new BasicNameValuePair("id_produk", id_produk));
			params.add(new BasicNameValuePair("jumlah", jumlah));
			// params.add(new BasicNameValuePair("id_ekspedisi", id_ekspedisi));
			params.add(new BasicNameValuePair("totalbeli", totalbeli));

			if (lastProduct == true) {
				params.add(new BasicNameValuePair("lastProduct", "true"));
				params.add(new BasicNameValuePair("grandTotal", String
						.valueOf(grandTotal)));
			}

			// getting JSON Object
			// Note that create pemesanan url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(
					url_create_detail_pemesanan, "POST", params);

			// check log cat fro response
			Log.d("Create Detail Pemesanan Response", json.toString());

			// check for success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					/*
					 * Intent a = new Intent(getApplicationContext(),
					 * MenuPemesanan.class);
					 * a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
					 * Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(a);
					 * 
					 * finish();
					 */

					Log.d("yuoho", "detail pemesanan sukses!");

				} else {
					// failed to create product
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

	}

	private void showCustomDialog() {
		// custom dialog
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.custom_dialog);
		dialog.setTitle("Terima Kasih");

		// set the custom dialog components - text, image and button
		TextView text = (TextView) dialog.findViewById(R.id.text);
		text.setText("TERIMAKASIH TELAH MELAKUKAN PEMESANAN, "
				+ "UNTUK KONFIRMASI PEMBAYRAN AKAN KAMI KIRIM KE EMAIL ANDA");
		ImageView image = (ImageView) dialog.findViewById(R.id.image);
		image.setImageResource(R.drawable.ic_launcher);

		Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent a = new Intent(getApplicationContext(),
						MenuPemesanan.class);
				a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_SINGLE_TOP);
				startActivity(a);

				finish();

				dialog.dismiss();
			}
		});

		dialog.show();
	}
	
	private void showCustomDialog2(String str) {
		// custom dialog
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.custom_dialog);
		dialog.setTitle("Info");

		// set the custom dialog components - text, image and button
		TextView text = (TextView) dialog.findViewById(R.id.text);
		text.setText(str);
		ImageView image = (ImageView) dialog.findViewById(R.id.image);
		image.setImageResource(R.drawable.ic_launcher);

		Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
		// if button is clicked, close the custom dialog
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				

				dialog.dismiss();
			}
		});

		dialog.show();
	}

	protected void loadPropinsi() {
		// TODO Auto-generated method stub

		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		// getting JSON string from URL
		JSONObject json = jParser.makeHttpRequest(url_daftar_propinsi, "GET",
				params);

		try {
			// Checking for SUCCESS TAG
			int success = json.getInt(TAG_SUCCESS);

			if (success == 1) {
				// Ada record Data (SUCCESS = 1)
				// Getting Array of daftar_produk
				daftar_propinsi = json.getJSONArray(TAG_DAFTAR_PROPINSI);

				namaProvinsi = new String[daftar_propinsi.length()];
				// Looping through All daftar_produk
				for (int i = 0; i < daftar_propinsi.length(); i++) {
					JSONObject c = daftar_propinsi.getJSONObject(i);

					// Storing each json item in variable
					String id_ekspedisi = c.getString(TAG_ID_EKSPEDISI);
					String propinsi = c.getString(TAG_PROPINSI);

					// creating new HashMap
					HashMap<String, String> map = new HashMap<String, String>();

					// adding each child node to HashMap key => value
					map.put(TAG_ID_EKSPEDISI, id_ekspedisi);
					map.put(TAG_PROPINSI, propinsi);

					Provinsi p = new Provinsi();
					p.setId_ekspedisi(id_ekspedisi);
					p.setPropinsi(propinsi);

					namaProvinsi[i] = propinsi;

					provinsies.add(p);

					Log.d("test propinsi", propinsi);

					// adding HashList to ArrayList
					// DaftarPropinsi.add(map);
				}
			} else {
				// Tidak ada record data (success = 0)
				// akan menutup aplikasi
				// finish();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, namaProvinsi);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerProvinsi.setAdapter(adapter);

		spinnerProvinsi.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView arg0, View arg1,
					int position, long id) {
				// TODO Auto-generated method stub

				setSpinner2(position);
			}

			@Override
			public void onNothingSelected(AdapterView arg0) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void setSpinner2(int position) {
		/*
		 * Toast.makeText(NewOrderActivity.this, "selected: " + position + " - "
		 * + namaProvinsi[position], Toast.LENGTH_SHORT).show();
		 */

		loadKota(namaProvinsi[position]);
	}

	protected void loadKota(String propinsi) {

		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("propinsi", propinsi));

		// getting JSON string from URL
		JSONObject json = jParser.makeHttpRequest(url_daftar_kota, "GET",
				params);

		try {
			// Checking for SUCCESS TAG
			int success = json.getInt(TAG_SUCCESS);

			if (success == 1) {
				daftar_kota = json.getJSONArray(TAG_DAFTAR_KOTA);

				namaKota = new String[daftar_kota.length()];
				// Looping through All
				for (int i = 0; i < daftar_kota.length(); i++) {
					JSONObject c = daftar_kota.getJSONObject(i);

					// Storing each json item in variable
					String id_ekspedisi = c.getString(TAG_ID_EKSPEDISI);
					String kota = c.getString(TAG_KOTA);

					// creating new HashMap
					HashMap<String, String> map = new HashMap<String, String>();

					// adding each child node to HashMap key => value
					map.put(TAG_ID_EKSPEDISI, id_ekspedisi);
					map.put(TAG_KOTA, kota);

					Kota k = new Kota();
					k.setId_ekspedisi(id_ekspedisi);
					k.setPropinsi(propinsi);
					k.setKota(kota);

					namaKota[i] = kota;

					kotas.add(k);

					Log.d("test kota", kota);

					// adding HashList to ArrayList
					// DaftarPropinsi.add(map);
				}
			} else {
				// Tidak ada record data (success = 0)
				// akan menutup aplikasi
				// finish();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, namaKota);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerKota.setAdapter(adapter);

		spinnerKota.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView arg0, View arg1,
					int position, long id) {
				// TODO Auto-generated method stub
				// setSpinner2(position);
			}

			@Override
			public void onNothingSelected(AdapterView arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	public class Provinsi {
		private String propinsi;
		private String id_ekspedisi;
		private int harga;

		public String getPropinsi() {
			return propinsi;
		}

		public void setPropinsi(String propinsi) {
			this.propinsi = propinsi;
		}

		public String getId_ekspedisi() {
			return id_ekspedisi;
		}

		public void setId_ekspedisi(String id_ekspedisi) {
			this.id_ekspedisi = id_ekspedisi;
		}

		public int getHarga() {
			return harga;
		}

		public void setHarga(int harga) {
			this.harga = harga;
		}

	}

	public class Kota {
		private String propinsi;
		private String id_ekspedisi;
		private String kota;
		private int harga;

		public String getKota() {
			return kota;
		}

		public void setKota(String kota) {
			this.kota = kota;
		}

		public String getPropinsi() {
			return propinsi;
		}

		public void setPropinsi(String propinsi) {
			this.propinsi = propinsi;
		}

		public String getId_ekspedisi() {
			return id_ekspedisi;
		}

		public void setId_ekspedisi(String id_ekspedisi) {
			this.id_ekspedisi = id_ekspedisi;
		}

		public int getHarga() {
			return harga;
		}

		public void setHarga(int harga) {
			this.harga = harga;
		}

	}
}
